$(function() {
//Declare variable
var  Code= $( "#Code" ),
			FirstName = $( "#FirstName" ),
			LastName = $( "#LastName" ),
			Birthday = $( "#BirthDay" ),
			Address=$("#Address"),
			Email=$("#Email"),
			CardID=$("#CardID"),
			Telephone=$("#Telephone"),
			CardNo=$("#CardNo"),
			Amount=$("#Amount"),
			allFields = $( [] ).add( Code )
								.add(FirstName)
								.add(LastName)
								.add(Birthday)
								.add(Address)
								.add(Email)
								.add(Telephone)
								.add(CardID)
								,
			SmartFields=$([]).add(CardNo)
							.add(Amount)
							,
			tips = $( ".validateTips" ),
			button_name="",
			url="a_customer.php", 
			ID="",
			AddTitle="Create new Customer",	
			EditTitle="Update Customer",	
			rowSelect="";
		
			
		//load first page
		LoadData(1,true);
		
		$("#btnSmart").button({
			icons:{
			 primary: "ui-icon-circle-plus"
			}
		});
		
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='12' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};		
				
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		function checkValidDate(ef,et,n){
			var splitarray_f = new Array(); 
			var splitarray_t = new Array(); 
			
			splitarray_f = ef.val().split("-");
			splitarray_t = et.val().split("-");
			
			var date1 = new Date(splitarray_f[2]+"/"+splitarray_f[1]+"/"+splitarray_f[0]);
			var date2 = new Date(splitarray_t[2]+"/"+splitarray_t[1]+"/"+splitarray_t[0]);
			 
			if (date1 > date2)
			{
				ef.addClass( "ui-state-error" );
				et.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			}
			else 
			{
				return true;
			}
		}
		function checkCombo(o,n){
		
			if(!(o.val())){
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			}else{
				return true;
			}
		}
		function AddErrorMessage(o,n){
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		}
		function getData(id){
 
			var dataSet={'id':id,'m':'detail'};  
			//alert(id);
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					var obj=eval('('+data+')');
				  	for (value in obj){
					//	alert(value);
						txt="#"+value;
					
						if (value=="BirthDay"){
							$("#BirthDay").datepicker("setDate" , obj[value]) ;
						}else if (value=="Sex"){
							if (obj[value]=="1") //Male
								$("#Sex_2").attr('checked','checked');
							else	//Female
								$("#Sex_1").attr('checked','checked');
								
						}else{
							$(txt).val(obj[value]);
						}
					}
				}
			});
		}
		
		function callAjax(obj,id){
			var rows=$("#rowCount").attr('innerHTML');
			var m=$("#mode").val();
			
			if (m=='edit'){
				rows=rowSelect.find("td").eq(0).html();
			}
			
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id,"rows":rows},
				success: function(data){
					
					if (m=='add'){
						if (data=='error'){
							AddErrorMessage(Code,Code.val() + ' already exists' );
						}else{
							//Insert data to first row.
							$( "#resultData tbody:first" ).prepend( data ); 
							//Set font color
							$( "#resultData tbody tr:first" ).css('color','blue');
							//Plus row number ;
							$("#rowCount").attr('innerHTML',parseInt(rows,10)+1);
							
							$( "#dialog-form" ).dialog( "close" );
						}
												
					}else if (m=='edit'){
						
						rowSelect.html(data);
					}
				
				}
			});
		}
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Form  Smart Purse 
		$( "#dialog-smartpurse" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 450,
			width: 550,
			zIndex:9999,
			modal: true,
			open: function() { 
				SmartFields.removeClass( "ui-state-error" );
				$("#dialog-confirm p").attr('innerText','Are you sure this card?');
				$.post(url,{"m":"card","id":ID},function(data){

						$( "#tbNewSmart tbody:first" ).prepend(data);
				});
				
			},
			close: function() {
				//alert('dd');
				$("#dialog-confirm p").attr('innerText','Are you sure this customer?');
				 $( "#tbNewSmart tbody tr" ).remove();
				 SmartFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 500,
			width: 400,
			zIndex:9999,
			modal: true,
			open: function() { 
				tips.text( "* fields are required." );
				if ($("#mode" ).val() =="edit" || $("#mode" ).val()=="view"){
					//getData(ID);
				}else{
					allFields.val( "" );
				}
			},
			close: function() {
				$("#Sex_1").attr('checked','checked');
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function getValue(){
			var o = {};
			//get name and value control 
			$( "#dialog-form" ).find('input').each(function(){
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					o[$(this).attr('id')].push($(this).val() || '');
				} else {
					o[$(this).attr('id')] = $(this).val() || '';
				}
			});
			//Sex
			o['Sex']=$('input[name=Sex]:checked').val();
			//Address 
			var _address = $( "#dialog-form" ).find('textarea').eq(0);
			o[_address.attr('id')] = _address.val() || '';
			
			return o;
		}
 
		//Submit form
		$('#Act').submit(function() { 
			//alert(ID);
			//$("#custid").val(ID);
			$("#hisFrom").val('m');
		}); 
		
		//History Button
		$(".btnHistory").live('click',function(){
			ID=$(this).parent().parent().find("td").eq(1).html();
			$("#custid").val(ID);
			$("#custname").val($(this).parent().parent().find("td").eq(3).html());
			$('#Act').submit();
		});
	 
		 
		
		$("#btnSearch").click(function(){

			LoadData(1,true);
			 
		});
		
	function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			
			 
			var dataSet={'m':'search2'
						,'name':$("#txtName_s").val()
						,'lastname':$("#txtLastName_s").val()
						,'code':$("#txtCode_s").val()
						,'birthdayfrom':$("#txtDateFrom").val()
						,'birthdayto':$("#txtDateTo").val()
						,'lastfrom':$("#txtLastedDateFrom").val()
						,'lastto':$("#txtLastedDateTo").val()
						,'cardid':$("#txtCardNo_s").val()
						,'page':page
						};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
				 //alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){
					// var p="<ul>";
					// for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						// p = p +'<li id="'+i+'" title="Page '+i+'" >'+i+'</li>';
					// }
					// p = p+"</ul>";
					//$("#paging_button ul").remove();
					//$("#paging_button").append(p);
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}
				}
				//$("#"+page).css({'background-color' : '#006699'});
			 });
		}
 
			
//	$("#paging_btn li").live('click',function(){
		//$("#paging_button li").css({'background-color' : ''});
 		//LoadData(this.id,false);

//	});	
	
	function setPaging(iTotal){
				 $("#paging_btn").paginate({
				count 		: iTotal,
				start 		: 1,
				display     : 10,
				border					: false,
				text_color  			: '#888',
				background_color    	: '#EEE',	
				text_hover_color  		: 'blue',
				background_hover_color	: '#CFCFCF',
				mouse					: 'press',
				onChange     			: function(page){
											LoadData(page,false);
										  }
			});
	}
		
});
	